package org.zp.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
	//url,用户名，密码，jdbc
			private static String url;
			private static String user;
			private static String pass;
			//每当加载文件时，该配置文件是整个项目运行期间只用一次,所以用静态
			static {
				Properties p = new Properties();
				//文件输入流
				try {
					String path = DBUtil.class.getClassLoader().getResource("").getPath();
					//D:\tomcat\apache-tomcat-8.5.55\webapps\TomcatTest\WEB-INF\classes\config
					path += "/config/dbconf.properties";
					System.out.println("地址"+path);
					p.load(new FileInputStream(path));
					//加载驱动
					Class.forName(p.getProperty("driver"));
					url = p.getProperty("url");
					user = p.getProperty("user");
					pass = p.getProperty("pass");
					
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			//测试连接
			public static Connection getConn() {
				try {
					Connection conn = DriverManager.getConnection(url,user,pass);
					System.out.println("连接成功");
					return conn;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					System.out.println("连接失败");
					e.printStackTrace();
					
				}
				
				
				return null;
				
			}
			//释放资源
			public static void close(Connection conn, PreparedStatement preparedstatement, ResultSet set) {
				try {
					if (preparedstatement != null) {
						preparedstatement.close();
					}
					if (set != null) {
						set.close();
					}
					if(conn != null) {
						conn.close();
					}

				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

}
